import os
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import threading

class DeleteRawFilesApp:
    def __init__(self, root):
        self.root = root
        self.root.title("删除Raw文件工具")
        self.root.geometry("600x400")
        self.root.resizable(True, True)
        
        # 设置样式
        style = ttk.Style()
        style.theme_use('clam')
        
        self.setup_ui()
        
    def setup_ui(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        
        # 标题
        title_label = ttk.Label(main_frame, text="删除Raw文件工具", font=("Arial", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=3, pady=(0, 20))
        
        # 输入路径选择
        ttk.Label(main_frame, text="输入文件夹:").grid(row=1, column=0, sticky=tk.W, pady=5)
        
        self.path_var = tk.StringVar()
        self.path_entry = ttk.Entry(main_frame, textvariable=self.path_var, width=50)
        self.path_entry.grid(row=1, column=1, sticky=(tk.W, tk.E), padx=(5, 5), pady=5)
        
        self.browse_button = ttk.Button(main_frame, text="浏览", command=self.browse_folder)
        self.browse_button.grid(row=1, column=2, pady=5)
        
        # 删除按钮
        self.delete_button = ttk.Button(main_frame, text="删除Raw文件", command=self.start_delete_process)
        self.delete_button.grid(row=2, column=0, columnspan=3, pady=20)
        
        # 进度条
        self.progress_var = tk.StringVar(value="准备就绪")
        self.progress_label = ttk.Label(main_frame, textvariable=self.progress_var)
        self.progress_label.grid(row=3, column=0, columnspan=3, pady=5)
        
        self.progress_bar = ttk.Progressbar(main_frame, mode='indeterminate')
        self.progress_bar.grid(row=4, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=5)
        
        # 日志文本框
        ttk.Label(main_frame, text="处理日志:").grid(row=5, column=0, sticky=tk.W, pady=(10, 5))
        
        # 创建文本框和滚动条
        text_frame = ttk.Frame(main_frame)
        text_frame.grid(row=6, column=0, columnspan=3, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5)
        text_frame.columnconfigure(0, weight=1)
        text_frame.rowconfigure(0, weight=1)
        
        self.log_text = tk.Text(text_frame, height=10, wrap=tk.WORD)
        scrollbar = ttk.Scrollbar(text_frame, orient=tk.VERTICAL, command=self.log_text.yview)
        self.log_text.configure(yscrollcommand=scrollbar.set)
        
        self.log_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
        
        # 配置主框架的行权重
        main_frame.rowconfigure(6, weight=1)
        
    def browse_folder(self):
        folder_path = filedialog.askdirectory(title="选择包含.spe文件的文件夹")
        if folder_path:
            self.path_var.set(folder_path)
            self.log_message(f"已选择文件夹: {folder_path}")
    
    def log_message(self, message):
        self.log_text.insert(tk.END, f"{message}\n")
        self.log_text.see(tk.END)
        self.root.update_idletasks()
    
    def start_delete_process(self):
        folder_path = self.path_var.get().strip()
        
        if not folder_path:
            messagebox.showerror("错误", "请选择输入文件夹！")
            return
        
        if not os.path.exists(folder_path):
            messagebox.showerror("错误", "选择的文件夹不存在！")
            return
        
        # 确认删除
        result = messagebox.askyesno("确认删除", "确认删除\"-raw\"文件？")
        if not result:
            return
        
        # 在新线程中执行删除操作
        self.delete_button.config(state='disabled')
        self.progress_bar.start()
        self.progress_var.set("正在处理...")
        
        thread = threading.Thread(target=self.delete_raw_files, args=(folder_path,))
        thread.daemon = True
        thread.start()
    
    def delete_raw_files(self, folder_path):
        try:
            self.log_message(f"开始扫描文件夹: {folder_path}")
            
            # 获取所有.spe文件
            spe_files = []
            raw_files = []
            
            for filename in os.listdir(folder_path):
                if filename.endswith('.spe'):
                    if filename.endswith('-raw.spe'):
                        raw_files.append(filename)
                    else:
                        spe_files.append(filename)
            
            self.log_message(f"找到 {len(spe_files)} 个.spe文件")
            self.log_message(f"找到 {len(raw_files)} 个-raw.spe文件")
            
            # 找出需要删除的raw文件
            files_to_delete = []
            for raw_file in raw_files:
                # 提取基础文件名（去掉-raw.spe后缀）
                base_name = raw_file[:-8]  # 去掉"-raw.spe"
                corresponding_spe = base_name + ".spe"
                
                if corresponding_spe in spe_files:
                    files_to_delete.append(raw_file)
            
            self.log_message(f"需要删除 {len(files_to_delete)} 个-raw.spe文件")
            
            # 删除文件
            deleted_count = 0
            for raw_file in files_to_delete:
                file_path = os.path.join(folder_path, raw_file)
                try:
                    os.remove(file_path)
                    self.log_message(f"已删除: {raw_file}")
                    deleted_count += 1
                except Exception as e:
                    self.log_message(f"删除失败 {raw_file}: {str(e)}")
            
            self.log_message(f"删除完成！共删除 {deleted_count} 个文件")
            
        except Exception as e:
            self.log_message(f"处理过程中出现错误: {str(e)}")
        finally:
            # 在主线程中更新UI
            self.root.after(0, self.finish_process)
    
    def finish_process(self):
        self.delete_button.config(state='normal')
        self.progress_bar.stop()
        self.progress_var.set("处理完成")
        messagebox.showinfo("完成", "文件删除操作已完成！")

def main():
    root = tk.Tk()
    app = DeleteRawFilesApp(root)
    root.mainloop()

if __name__ == "__main__":
    main() 